<!--
 * Copyright © 2025 上海火金网络科技有限公司. All rights reserved.
 * Merchant Management - 商户管理
 *
 * 功能：管理商户基本信息，配置商户与服务商的关联关系
 * 版本：1.0.0
 *
 * Website: https://www.anypay.com
-->

<template>
  <div class="anypay-apple-list-page">
    <div class="anypay-apple-page-header">
      <h1>商户管理</h1>
      <p>管理商户基本信息，配置商户与服务商的关联关系</p>
    </div>

    <!-- 搜索区域 -->
    <div class="anypay-apple-card anypay-apple-mb-6">
      <a-card>
        <div class="search-container standard">
          <!-- 商户名称 -->
          <div class="search-field">
            <label class="search-label">商户名称:</label>
            <a-input
              v-model:value="searchForm.merchantName"
              placeholder="请输入商户名称"
              class="search-input"
              allowClear
            />
          </div>

          <!-- 商户ID -->
          <div class="search-field">
            <label class="search-label">商户ID:</label>
            <a-input
              v-model:value="searchForm.merchantId"
              placeholder="请输入商户ID"
              class="search-input-small"
              allowClear
            />
          </div>

          <!-- 服务商 -->
          <div class="search-field">
            <label class="search-label">服务商:</label>
            <a-select
              v-model:value="searchForm.providerId"
              placeholder="请选择服务商"
              class="search-select-large"
              allowClear
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option
                v-for="provider in serviceProviders"
                :key="provider.providerId"
                :value="provider.providerId"
              >
                {{ provider.providerName }}
              </a-select-option>
            </a-select>
          </div>

          <!-- 状态 -->
          <div class="search-field">
            <label class="search-label">状态:</label>
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              class="search-select"
              allowClear
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="0">停用</a-select-option>
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="2">审核中</a-select-option>
              <a-select-option :value="3">审核失败</a-select-option>
            </a-select>
          </div>

          <!-- 联系人 -->
          <div class="search-field">
            <label class="search-label">联系人:</label>
            <a-input
              v-model:value="searchForm.contactName"
              placeholder="请输入联系人姓名"
              class="search-input"
              allowClear
            />
          </div>

          <!-- 联系电话 -->
          <div class="search-field">
            <label class="search-label">联系电话:</label>
            <a-input
              v-model:value="searchForm.contactTelephone"
              placeholder="请输入联系电话"
              class="search-input"
              allowClear
            />
          </div>

          <!-- 操作按钮 -->
          <div class="search-actions">
            <a-button type="primary" @click="handleSearch" class="search-btn">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="search-btn">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="anypay-apple-card">
      <a-card>
        <div class="anypay-apple-table anypay-apple-toolbar">
          <AnyTable
            ref="merchantTable"
            :autoLoad="true"
            :dataLoader="loadMerchantData"
            :tableColumns="tableColumns"
            :searchParams="searchParams"
            :tableScroll="{ x: 'max-content' }"
            tableRowKey="merchantId"
            @loadComplete="handleLoadComplete"
          >
            <template #tableToolbar>
              <a-space :size="12">
                <a-button type="primary" @click="addMerchant">
                  <PlusOutlined /> 新增商户
                </a-button>
              </a-space>
            </template>
            <template #tableCell="{ column, record }">
              <template v-if="column.key === 'providerName'">
                <div class="provider-info">
                  <a-tag color="blue">{{ getProviderName(record.providerId) }}</a-tag>
                  <div class="provider-id">{{ record.providerId }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag
                  :color="record.status === 0 ? undefined : getStatusColor(record.status)"
                  :class="record.status === 0 ? 'status-disabled' : ''"
                >
                  {{ getStatusText(record.status) }}
                </a-tag>
              </template>
                              <template v-else-if="column.key === 'op'">
                  <div class="anypay-apple-actions">
                    <a-space>
                      <a-button type="link" @click="editMerchant(record)">
                        <EditOutlined />编辑
                      </a-button>
                      <a-button type="link" @click="viewMerchant(record)">
                        <EyeOutlined />查看
                      </a-button>
                      <a-dropdown placement="bottomRight">
                        <a-button type="link" size="small">
                          <MoreOutlined />
                          更多
                        </a-button>
                        <template #overlay>
                          <a-menu>
                            <a-menu-item key="toggle" @click="handleToggleStatus(record)">
                              <SwapOutlined />
                              {{ record.status === 1 ? '停用' : '启用' }}
                            </a-menu-item>
                            <a-menu-divider />
                            <a-menu-item key="delete" @click="deleteMerchant(record.merchantId)" style="color: #ff4d4f;">
                              <DeleteOutlined />
                              删除
                            </a-menu-item>
                          </a-menu>
                        </template>
                      </a-dropdown>
                    </a-space>
                  </div>
                </template>
            </template>
          </AnyTable>
        </div>
      </a-card>
    </div>

    <!-- 商户详情和编辑组件 -->
    <MerchantDetail ref="merchantDetailRef" />
    <MerchantEdit ref="merchantEditRef" :callbackFunc="searchMerchants" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance } from 'vue'
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  SwapOutlined,
  MoreOutlined
} from '@ant-design/icons-vue'
import {
  merchants,
  getMerchantStatusName,
  getMerchantStatusColor,
  mockLoadMerchants,
  type Merchant
} from '@/mock/merchants'
import { serviceProviders, type ServiceProvider } from '@/mock/service-providers'
import MerchantDetail from './merchant-detail.vue'
import MerchantEdit from './merchant-edit.vue'
import AnyTable from '@/components/AnyTable.vue'

// 获取全局消息提示
const { $AnyMessageBox } = getCurrentInstance()!.appContext.config.globalProperties

// 组件引用
const merchantTable = ref()
const merchantDetailRef = ref()
const merchantEditRef = ref()

// 搜索表单
const searchForm = reactive({
  merchantName: '',
  merchantId: '',
  providerId: '',
  status: '',
  contactName: '',
  contactTelephone: ''
})

// 搜索参数
const searchParams = reactive<{
  merchantName?: string
  merchantId?: string
  providerId?: string
  status?: number
  contactName?: string
  contactTelephone?: string
}>({})

// 表格列定义
const tableColumns = [
  {
    title: '商户名称',
    dataIndex: 'merchantName',
    key: 'merchantName',
    width: 150,
    fixed: 'left'
  },
  {
    title: '商户ID',
    dataIndex: 'merchantId',
    key: 'merchantId',
    width: 140
  },
  {
    title: '服务商',
    key: 'providerName',
    width: 160
  },
  {
    title: '联系人',
    dataIndex: 'contactName',
    key: 'contactName',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'contactTelephone',
    key: 'contactTelephone',
    width: 120
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 150
  },
  {
    title: '操作',
    key: 'op',
    width: 200,
    align: 'center',
    fixed: 'right'
  }
]

// 数据加载函数
const loadMerchantData = async (params: any) => {
  try {
    const response = await mockLoadMerchants(params) as any
    return {
      records: response.data || [],
      total: response.total || 0
    }
  } catch (error) {
    console.error('Failed to load merchant data:', error)
    return { records: [], total: 0 }
  }
}

// 加载完成回调
const handleLoadComplete = () => {
  console.log('Merchant data loaded successfully')
}

// 获取服务商名称
const getProviderName = (providerId: string): string => {
  const provider = serviceProviders.find(p => p.providerId === providerId)
  return provider ? provider.providerName : providerId
}

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '停用',
    1: '启用',
    2: '审核中',
    3: '审核失败'
  }
  return statusMap[status] || '未知'
}

// 获取状态颜色（停用状态使用自定义CSS类）
const getStatusColor = (status: number): string => {
  switch (status) {
    case 1: // 启用
      return 'green'
    case 2: // 审核中
      return 'orange'
    case 3: // 审核失败
      return 'red'
    default:
      return 'default'
  }
}

// 搜索功能
const handleSearch = () => {
  // 清空之前的搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  // 只添加非空的搜索条件
  if (searchForm.merchantName) {
    searchParams.merchantName = searchForm.merchantName
  }
  if (searchForm.merchantId) {
    searchParams.merchantId = searchForm.merchantId
  }
  if (searchForm.providerId) {
    searchParams.providerId = searchForm.providerId
  }
  if (searchForm.status !== '') {
    searchParams.status = Number(searchForm.status)
  }
  if (searchForm.contactName) {
    searchParams.contactName = searchForm.contactName
  }
  if (searchForm.contactTelephone) {
    searchParams.contactTelephone = searchForm.contactTelephone
  }

  searchMerchants()
}

// 重置搜索
const handleReset = () => {
  // 清空搜索表单
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = ''
  })

  // 清空搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  searchMerchants()
}

// 搜索和重置
const searchMerchants = () => {
  merchantTable.value?.refreshTable(true)
}

// CRUD操作
const addMerchant = () => {
  merchantEditRef.value?.show(null)
}

const editMerchant = (merchant: Merchant) => {
  merchantEditRef.value?.show(merchant)
}

const viewMerchant = (merchant: Merchant) => {
  merchantDetailRef.value?.openModal(merchant)
}

// 删除商户
const deleteMerchant = (merchantId: string) => {
  $AnyMessageBox.confirmDanger('确认删除该商户信息？', '删除后无法恢复，请谨慎操作', () => {
    // 这里应该调用真实的删除API
    // apiMerchantDelete(merchantId).then(() => {
    $AnyMessageBox.message.success('删除成功')
    searchMerchants()
    // })
  })
}

// 切换状态
const handleToggleStatus = (merchant: Merchant) => {
  const newStatus = merchant.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '停用'

  $AnyMessageBox.confirm(
    `确认${action}该商户？`,
    `${action}后商户状态将立即生效`,
    () => {
      // 这里应该调用真实的状态切换API
      // apiMerchantToggleStatus(merchant.merchantId, newStatus).then(() => {
      merchant.status = newStatus
      $AnyMessageBox.message.success(`${action}成功`)
      // })
    }
  )
}
</script>

<style scoped>
@import '../common/list-page.css';
</style>

